package cn.bytecollege.controller;

import cn.bytecollege.constant.Resource;
import cn.bytecollege.entity.Admin;
import cn.bytecollege.service.AdminService;
import cn.bytecollege.util.MD5Util;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "AdminLoginController", value = "/admin/login")
public class AdminLoginController extends HttpServlet {
    AdminService adminService = null;
    public AdminLoginController(){
        adminService = new AdminService();
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher(Resource.PAGE_LOCATION+"login.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String msg = null;

        //获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //调用service方法获取数据库中数据
        Admin admin = adminService.findByAdminName(username);

        //判断输入的管理员账号密码是否错误
        if (admin == null){
            msg = "用户名不存在";
            request.setAttribute("msg",msg);
            request.getRequestDispatcher(Resource.PAGE_LOCATION+"/login.jsp").forward(request,response);
            return;
        }
        if (username.equals(admin.getAdminName()) && MD5Util.md5Encode(password).equals(admin.getAdminPassword())){
            //session中封装用户数据
            HttpSession session = request.getSession();
            session.setAttribute("admin",admin);
//            request.getRequestDispatcher("/index.jsp").forward(request,response);
            response.sendRedirect(request.getContextPath()+"/index");
        }else {
            msg = "用户名错误或者密码错误";
            request.setAttribute("msg",msg);
            request.getRequestDispatcher(Resource.PAGE_LOCATION+"login.jsp").forward(request,response);
        }
    }
}
